//notation: js file can only use this kind of comments
//since comments will cause error when use in webview.loadurl,
//comments will be remove by java use regexp
//version 1.0.3
(function () {
    if (window.LvUJsBridge) {
        return;
    }
    var messagingIframe;
    var sendMessageQueue = [];
    var receiveMessageQueue = [];
    var messageHandlers = {};

    var CUSTOM_PROTOCOL_SCHEME = 'vpclub';
    var QUEUE_HAS_MESSAGE = '__QUEUE_MESSAGE__/';

    var responseCallbacks = {};
    var uniqueId = 1;

    function _createQueueReadyIframe(doc) {
        messagingIframe = doc.createElement('iframe');
        messagingIframe.style.display = 'none';
        messagingIframe.src = 'http://__bridge_loaded__';
        doc.documentElement.appendChild(messagingIframe);
    }

    function isAndroid() {
        var ua = navigator.userAgent.toLowerCase();
        var isA = ua.indexOf("android") > -1;
        if (isA) {
            return true;
        }
        return false;
    }

    function isIphone() {
        var ua = navigator.userAgent.toLowerCase();
        var isIph = ua.indexOf("iphone") > -1;
        if (isIph) {
            return true;
        }
        return false;
    }

    //set default messageHandler
    function init(messageHandler) {
        if (LvUJsBridge._messageHandler) {
            throw new Error('LvUJsBridge.init called twice');
        }
        LvUJsBridge._messageHandler = messageHandler;
        var receivedMessages = receiveMessageQueue;
        // alert('null')
        receiveMessageQueue = null;
        for (var i = 0; i < receivedMessages.length; i++) {
            _dispatchMessageFromNative(receivedMessages[i]);
        }
    }

    function send(data, responseCallback) {
        _doSend({
            data: data
        }, responseCallback);
    }

    function registerHandler(handlerName, handler) {
        messageHandlers[handlerName] = handler;
    }

    function callHandler(handlerName, data, responseCallback) {
        _doSend({
            handlerName: handlerName,
            data: data
        }, responseCallback);
    }

    //sendMessage add message, 触发native处理 sendMessage
    function _doSend(message, responseCallback) {
        if (responseCallback) {
            var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
            responseCallbacks[callbackId] = responseCallback;
            message.callbackId = callbackId;
        }

        sendMessageQueue.push(message);
        messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
        if (isIphone()) {
            messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE.slice(0, -1);
        }
    }

    // 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容
    function _fetchQueue() {
        var messageQueueString = JSON.stringify(sendMessageQueue);
        sendMessageQueue = [];
        //add by hq
        if (isIphone()) {
            return messageQueueString;
            //android can't read directly the return data, so we can reload iframe src to communicate with java
        } else if (isAndroid()) {
            messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + messageQueueString;
        }
    }

    //提供给native使用,
    function _dispatchMessageFromNative(messageJSON) {
        setTimeout(function () {
            var message = JSON.parse(messageJSON);
            var responseCallback;
            //java call finished, now need to call js callback function
            if (message.responseId) {
                responseCallback = responseCallbacks[message.responseId];
                if (!responseCallback) {
                    return;
                }
                if (isIphone()) {
                    responseCallback(message.responseData);
                } else {
                    if (message.responseData) {
                        responseCallback(eval('(' + message.responseData + ')'));
                    } else {
                        responseCallback(message.responseData);
                    }
                }
                delete responseCallbacks[message.responseId];
            } else {
                //直接发送
                if (message.callbackId) {
                    var callbackResponseId = message.callbackId;
                    responseCallback = function (responseData) {
                        _doSend({
                            responseId: callbackResponseId,
                            responseData: responseData
                        });
                    };
                }

                var handler = LvUJsBridge._messageHandler;
                if (message.handlerName) {
                    handler = messageHandlers[message.handlerName];
                }
                //查找指定handler
                try {
                    handler(message.data, responseCallback);
                } catch (exception) {
                    if (typeof console != 'undefined') {
                        console.log("LvUJsBridge: WARNING: javascript handler threw.", message, exception);
                    }
                }
            }
        });
    }

    //提供给native调用,receiveMessageQueue 在会在页面加载完后赋值为null,所以
    function _handleMessageFromNative(messageJSON) {

        if (receiveMessageQueue) {
            receiveMessageQueue.push(messageJSON);
        } else {
            _dispatchMessageFromNative(messageJSON);
        }
    }

    var LvUJsBridge = window.LvUJsBridge = {
        init: init,
        send: send,
        on: registerHandler,
        invoke: callHandler,
        _fetchQueue: _fetchQueue,
        _handleMessageFromNative: _handleMessageFromNative
    };

    var doc = document;
    _createQueueReadyIframe(doc);
    var readyEvent = doc.createEvent('Events');
    readyEvent.initEvent('LvUJsBridgeReady');
    readyEvent.bridge = LvUJsBridge;
    doc.dispatchEvent(readyEvent);
})();


//WebViewJavaScriptBridge 初始化
(function (callback) {
    if (window.LvUJsBridge) {
        callback(LvUJsBridge)
    } else {
        if (document.addEventListener) {
            document.addEventListener(
                'LvUJsBridgeReady',
                function () {
                    callback(LvUJsBridge)
                },
                false
            );
        }
    }
})
    (function (bridge) { //init
        bridge.init(function (message, responseCallback) {
            var data = {
                'jsResponse': 'Wee!'
            };
            responseCallback(data);
        });
        clientShare = bridge;
    });


/*
 * js 触发 原生函数 
 * triggerTips:约定的标识
 * params: 传递给原生的参数
 * callback 接收响应回调
 */
function triggerNative(triggerTips, params, callback) {
    if (window.LvUJsBridge) {
        try {
            window.LvUJsBridge.invoke(triggerTips, params, callback);
        } catch (ex) {
            alert("1当前APP不支持此功能，请升级您的版本");
        }
    } else {
        alert("2当前APP不支持此功能，请升级您的版本");
    }
}

/*
 ** 客户端 触发 js 方法
 *  triggerTips:约定的标识
 *  callback:调函数，可传参 
 */
function triggerJS(triggerTips, callback) {
    if (window.LvUJsBridge) {
        try {
            window.LvUJsBridge.on(triggerTips, callback);
        } catch (ex) {
            alert("3当前APP不支持此功能，请升级您的版本");
        }
    } else {
        alert("4当前APP不支持此功能，请升级您的版本");
    }
}



var hsh = {
    CheckUrl: function () {
        var checkUrl = window.location.href;
        var allUrl = checkUrl.split('?');
        if (allUrl.length > 1) {
            var urlContent = allUrl[1].split('&');
            var keyValueDX = {};
            urlContent.forEach(function (item) {
                var objArr = item.split('='); // ['a', '1'];
                keyValueDX[objArr[0]] = objArr[1];
            })
        }
        return keyValueDX || {};
    },
    // 获取url中的token
    getToken: function (callback) {
        if (typeof callback == 'function') {
            callback(this.CheckUrl().token);
        }
    },
    // 判断是否在客户端内
    isApp: function () {
        if (this.CheckUrl().token) {
            return true
        } else {
            return false
        }
    },
    // 注册分享信息
    registerShare: function (shareData) {
        window.LvUJsBridge.invoke('registerShare', shareData);
    },
    // 触发客户端左上角返回按钮事件
    goBack: function () {
        window.LvUJsBridge.invoke('goBack', {}, function (response) { });
    },
    // 拉起分享框
    share: function (shareData) {
        window.LvUJsBridge.invoke('share', shareData);
    },
    // 接收分享结果方法
    checkMessage: function (callback) {
        window.LvUJsBridge.on('returnMessage', callback);
    },
    // 客户端通过js桥传递token
    getTokenNew: function (callback) {
        window.LvUJsBridge.invoke('getToken', {}, callback);
    },
    // 客户端修改userAgent，h5判断是否在客户端内
    isAppNew: function () {
        var ua = window.navigator.userAgent;
        return ua.indexOf('app_hsh') != -1 ? 1 : 0;
    },
    // 跳至短信
    sendMessage: function (messageData) {
        window.LvUJsBridge.invoke('sendMessage', messageData);
    },
    // 手机拨号
    callPhone: function (tel) {
        window.LvUJsBridge.invoke('callPhone', tel);
    },
    // 调起摄像头扫码
    scanCode: function (callback) {
        window.LvUJsBridge.invoke('scanCode', {}, callback);
    }
}


// 获取单点登录token
// if(hsh.isApp()){
//     hsh.getToken(function(responssData){
//         console.log(responssData);
//     })
// }

// 注册分享信息允许分享
// if (hsh.isAppNew()) {
//     var shareData = {
//         // 分享标题
//         title: "分享标题",
//         // 分享描述文字
//         desc: "分享描述文字",
//         // 分享链接
//         link: "分享链接",
//         // 分享图片
//         imgUrl: "分享图片链接",
//         // 判断是否允许分享标识
//         isShare: '1'
//     };
//     // 注册分享
//     hsh.registerShare(shareData);
// }


// 隐藏右上角分享按钮
// if (hsh.isApp()) {
//     var shareData = {
//         // 分享标题
//         title: "",
//         // 分享描述文字
//         desc: "",
//         // 分享链接
//         link: "",
//         // 分享图片
//         imgUrl: "",
//         // 判断是否允许分享标识
//         isShare: '0'
//     };
//     // 注册分享
//     hsh.registerShare(shareData);
// }

// 触发客户端返回按钮
// hsh.goBack();

// 拉起分享框
// if(hsh.isApp()){
//     hsh.share(sharaData);
// }

// 兼容老版本新单点登录方式
// if (hsh.isApp()) {
//     getToken(function (urlToken) {
//         console.log(urlToken);
//     })
// } else {
//     if (hsh.isAppNew()) {
//         hsh.getTokenNew(function (response) {
//             console.log(response.token);
//         })
//     }
// }

// 若需要客户端传递操作成功标识
// if (isAppNew()) {
//     hsh.checkMessage(function (response) {
//         console.log(response);
//             response.result = true;
//     })
// }

// 手机拨号
// if (isAppNew()) {
//     var tel = {
//         phone: '12345612312'
//     };
//     hsh.callPhone(tel);
// }

// 调起摄像头扫码
// if (isAppNew()) {
//     hsh.scanCode(function (response) {
//         alert(JSON.stringify(response));
//     });
// }
